package com.smartEdu.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.jsoup.Jsoup;

public class IOUtils {
	/*
	 * 指定编码格式，把输入流转化成字符串
	 * 
	 * @param is
	 * @return
	 * @throws IOException
	 * */
	public static String getHtml(InputStream is, String encoding)
			throws IOException{
		ByteArrayOutputStream bos = 
				new ByteArrayOutputStream();
		byte[] buffer = new byte[1024];
		int len = 0 ;
		while((len = is.read(buffer)) != -1){
			bos.write(buffer, 0, len);
		}
		is.close();
		return new String(bos.toByteArray(),encoding);
	}
	
	/*
	 * 判断字符编码集
	 * @param str
	 * @return
	 * */
	public static String getEncoding(String str){
		String encode = "utf-8";
		try{
			if(str.equals(new String(str.getBytes(encode),encode))){
				String s = encode;
				return s;
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		encode = "ISO-8859-1";
		try{
			if(str.equals(new String(str.getBytes(encode),encode))){
				String s1 = encode;
				return s1;
			}
		}catch(Exception e1){
			e1.printStackTrace();
		}
		encode = "GB2312";
		try{
			if(str.equals(new String(str.getBytes(encode),encode))){
				String s2 = encode;
				return s2;
			}
		}catch(Exception e2){
			e2.printStackTrace();
		}
		encode = "GBK";
		try{
			if(str.equals(new String(str.getBytes(encode),encode))){
				String s3 = encode;
				return s3;
			}
		}catch(Exception e3){
			e3.printStackTrace();
		}
		return "未知";	
	}
/*
 * 获取隐藏字段 encoded 的值
 * 
 * @param url
 * @param cookie
 * @param referer
 * @return
 * @throws UnsupportedOperationException
 * @throws ClientProtocolException
 * @throws IOException
 * */	
	public static String getEncoded(String url,String cookie,
			String referer) throws UnsupportedOperationException,
			ClientProtocolException,IOException{
		CloseableHttpClient client = HttpClients.createDefault();
		HttpGet getEncoded = new HttpGet(url);
		getEncoded.setHeader("Cookie",cookie);
		getEncoded.setHeader(referer, referer);//设置头信息
		String s = IOUtils.getHtml(client.execute(getEncoded)
				.getEntity().getContent(),"utf-8");
		String encoded = Jsoup.parse(s).select("input[name=Encoded]")
				.val();
		client.close();
		return encoded;	
	}
}
